package com.fingard.dsp.bank.directbank.cqsx01;

import java.text.SimpleDateFormat;
import java.util.*;

import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

/**
 * Created by dalt on 2017/6/20.
 */
public class CQSX01SinglePay extends CQSX01Base implements ISinglePay {

    /**
     * 跨行转账
     */
    public RetAtsSingle d_1908_SglPayBetweenDifferentBank(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        try {
            StringBuilder reqXml = new StringBuilder();
            reqXml.append(String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Message><Head>" +
                            "<TrsCode>B2ECrossBankTransfer</TrsCode><ERPTrsTimestamp>" +
                            "%s</ERPTrsTimestamp><ERPJnlNo>%s</ERPJnlNo>" +
                            "</Head><Body><List>",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                    parseSeq(reqHeader.reqSeqID)));
            reqXml.append(String.format("<Map><PayerAcNo>%s</PayerAcNo><PayerAcName>" +
                            "%s</PayerAcName><PayeeAcNo>%s" +
                            "</PayeeAcNo><PayeeAcName>%s</PayeeAcName>" +
                            "<Amount>%s</Amount><Currency>%s</Currency><Remark>%s</Remark>" +
                            "<DrecCode>%s</DrecCode><UnionDeptId>%s</UnionDeptId>" +
                            "<PayeeBankName>%s</PayeeBankName><Priority>%s</Priority></Map>",
                    p_req1908.singleDetail.payAct, p_req1908.singleDetail.payName,
                    p_req1908.singleDetail.recAct, p_req1908.singleDetail.recName,
                    p_req1908.singleDetail.payAmount, super.convertCurToBank(p_req1908.singleDetail.payCur),
                    p_req1908.singleDetail.purpose, p_req1908.singleDetail.cnapsCode,
                    /*p_req1908.singleDetail.recBankCode*/p_req1908.singleDetail.cnapsCode, p_req1908.singleDetail.recBankName,
                    p_req1908.singleDetail.paySpd.equals("1") ? "0" : "1"));
            reqXml.append("</List></Body></Message>");
            //发送报文给银行同时获取结果
            String[] tmpStrRet = super.sendToBank(reqXml.toString().replace("null", ""), "B2ECrossBankTransfer");
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                    String tmpRetMessage = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = tmpRetMessage;
                        retDetail.transState = tmpRetCode;
                        retDetail.payInfoCode = tmpRetCode;
                        retDetail.reqSeqID = p_req1908.reqHeader.reqSeqID;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpRetMessage;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
            retAts.writeRetDetail(retDetail);
        } catch (Exception e) {
            //此时retContent为错误信息
            e.printStackTrace();
            retAts.writeRespCode(ConnState.FAIL);
            retAts.writeRespInfo(e.toString());
        }
        return retAts;
    }

    /**
     * 同行转账
     */
    public RetAtsSingle d_1908_SglPayBetweenSameBank(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);

        try {
            StringBuilder reqXml = new StringBuilder();
            reqXml.append(String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Message><Head><TrsCode>B2EBankInnerTransfer</TrsCode>" +
                            "<ERPTrsTimestamp>%s</ERPTrsTimestamp><ERPJnlNo>%s</ERPJnlNo></Head><Body><List>",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                    parseSeq(reqHeader.reqSeqID)));
            reqXml.append(String.format("<Map><PayerAcNo>%s</PayerAcNo><PayerAcName>%s</PayerAcName>" +
                            "<PayeeAcNo>%s</PayeeAcNo><PayeeAcName>%s" +
                            "</PayeeAcName><Amount>%s</Amount><PayerCurrency>%s</PayerCurrency>" +
                            "<Remark>%s</Remark></Map>",
                    p_req1908.singleDetail.payAct, p_req1908.singleDetail.payName,
                    p_req1908.singleDetail.recAct, p_req1908.singleDetail.recName,
                    p_req1908.singleDetail.payAmount, super.convertCurToBank(p_req1908.singleDetail.payCur),
                    p_req1908.singleDetail.purpose));
            reqXml.append("</List></Body></Message>");
            //发送报文给银行

            String[] tmpStrRet = sendToBank(reqXml.toString().replace("null", ""), "B2EBankInnerTransfer");
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                    String tmpRetMessage = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = tmpRetMessage;
                        retDetail.transState = tmpRetCode;
                        retDetail.payInfoCode = tmpRetCode;
                        retDetail.reqSeqID = p_req1908.reqHeader.reqSeqID;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpRetMessage;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
            retAts.writeRetDetail(retDetail);
        } catch (Exception e) {
            //此时retContent为错误信息
            e.printStackTrace();
            retAts.writeRespCode(ConnState.FAIL);
            retAts.writeRespInfo(e.toString());
        }
        return retAts;
    }

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        return p_req1908.singleDetail.sameBnk.equals("1") ? d_1908_SglPayBetweenSameBank(p_req1908)
                : d_1908_SglPayBetweenDifferentBank(p_req1908);
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        StringBuilder reqXml = new StringBuilder();
        reqXml.append(String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<Message>\n" +
                        "<Head>\n" +
                        "<ERPJnlNo>%s</ERPJnlNo>\n" +
                        "<TrsCode>B2EPaymentStatQry</TrsCode>\n" +
                        "<ERPTrsTimestamp>%s</ERPTrsTimestamp>\n" +
                        "</Head>\n" +
                        "<Body>\n" +
                        "<List>",
                parseSeq(reqHeader.reqSeqID), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
        ));
        reqXml.append(String.format("<Map>\n" +
                        "<OldJnlNo>%s</OldJnlNo>\n" +
                        "<OldTrsDate>%s</OldTrsDate>\n" +
                        "<PayAcnt>%s</PayAcnt>\n" +
                        "<RcvAcnt>%s</RcvAcnt>\n" +
                        "<Amount>%s</Amount>\n" +
                        "<CifNo>%s</CifNo>\n" +
                        "<AcNo>%s</AcNo>\n" +
                        "<Priority>%s</Priority>\n" +
                        "<Bak1></Bak1>\n" +
                        "</Map>\n",
                parseSeq(reqHeader.reqSeqID),
                new SimpleDateFormat("yyyy-MM-dd").format(p_req1944.getBgnDateTime()),
                p_req1944.payAct, p_req1944.recAct,
                p_req1944.payAmount, super.bankFront.org,
                p_req1944.payAct, "0"));
        reqXml.append("</List></Body></Message>");
        //发送报文给银行
        try {
            String[] tmpStrRet = sendToBank(reqXml.toString().replace("null", ""), "B2EPaymentStatQry");
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String tmpRetMessage = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if(tmpBkReader.read("/Message/Body/List/Map")) {
                        if (isActiveRetCode(tmpRetCode)) {
                            retDetail.respCode = "0";
                            retDetail.reqSeqID = tmpBkReader.readedXElement.getSingleText("OldJnlNo");
                            retDetail.respInfo = tmpBkReader.readedXElement.getSingleText("ReturnMsg");
                            retDetail.transState = retDetail.respCode + "+" + tmpBkReader.readedXElement.getSingleText("TranStat");
                            retDetail.payInfoCode = retDetail.transState;
                        } else {
                            retDetail.respCode = "-1";
                            retDetail.respInfo = tmpRetMessage;
                        }
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
